/*
 * Copyright (C) 2018 Arm Limited or its affiliates. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Description: Example code for running keyword spotting on Cortex-M boards
 */
#include "rtthread.h"
#include "bf0_hal.h"
#include "drv_io.h"
#include "stdio.h"
#include "string.h"
#include "audio.h"
#include "drv_flash.h"


#define USE_DNN   1

#if USE_DNN==1
  #include "kws_dnn.h"
#else
  #include "kws_ds_cnn.h"
#endif

//#include "wav_data.h"

int16_t audio_buffer[16000];//=WAVE_DATA;



int main()
{
  char output_class[12][8] = {"Silence", "Unknown","yes","no","up","down","left","right","on","off","stop","go"};
  rt_tick_t start,end;

  //rt_kprintf("Hello world! %d\n",RT_TICK_PER_SECOND);
#if USE_DNN==1
    KWS_DNN kws(audio_buffer);
#else
    KWS_DS_CNN kws(audio_buffer);
#endif

  //audio_encoder_open();
  //mic_open();
  //speaker_open();

  /* semaphore initialiation. */
  //comm_init();
  //start_recording();
  /* Play recording file. */
  //recording_play();
  audio_init();
 //T.start();
 //int start=T.read_us();
 // kws.extract_features(); //extract mfcc features
 // kws.classify();	  //classify using dnn
 // int end=T.read_us();
 // T.stop();
  //int max_ind = kws.get_top_class(kws.output);
  //rt_kprintf("Total time : %d us\r\n",end-start);
  //rt_kprintf("Detected %s (%d%%)\r\n",output_class[max_ind],((int)kws.output[max_ind]*100/128));
  
  while(1){ 
    if(get_audio_ok(audio_buffer)){
#if 1
        start = rt_tick_get_millisecond();
        kws.extract_features(); //extract mfcc features
        kws.classify();	  //classify using dnn
        end = rt_tick_get_millisecond();

        rt_kprintf("Total time : %d ms\r\n",end-start);

        int max_ind = kws.get_top_class(kws.output);
        rt_kprintf("Detected %s (%d%%)\r\n",output_class[max_ind],((int)kws.output[max_ind]*100/128));
#endif
    }
    else
        rt_thread_mdelay(100);
  }
  return 0;
}
